package visiopuce.ui;

import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.eclipse.jface.bindings.keys.KeyStroke;
import org.eclipse.jface.bindings.keys.ParseException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.SimpleContentProposalProvider;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import visiopuce.ApplicationContexte;
import visiopuce.objets.Analyse;
import visiopuce.objets.Cotation;
import visiopuce.objets.Personne;
import visiopuce.objets.Prelevement;
import visiopuce.objets.TypeCotation;
import visiopuce.service.AnalyseServiceImpl;
import visiopuce.service.CotationServiceImpl;
import visiopuce.service.DroitServiceImpl;
import visiopuce.service.PrelevementServiceImpl;
import visiopuce.service.ReferentielServiceImpl;
import visiopuce.ui.providers.CotationComboEditingSupport;
import visiopuce.ui.providers.CotationDateEditingSupport;

public class CotationDialog extends Dialog {

	private Personne personne;
	private Table table_1;
	private Table table;
	private TableViewer tableCotation;
	private ArrayList<TypeCotation> typeCotations;
	private String text;
	private Text tNum;
	private Button btnPlus;
	private ContentProposalAdapter adapter;

	public CotationDialog(Shell parentShell, Personne personne, String text) {
		super(parentShell);
		this.personne = personne;
		this.text = text;
		setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
		setBlockOnOpen(true);
	}

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Cotation du patient : " + personne.getPrenom() + " " + personne.getNom());
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		Composite container = (Composite) super.createDialogArea(parent);
		if (text != null) {
			Label lbltxt = new Label(container, SWT.BORDER);
			lbltxt.setText(text);
			lbltxt.setAlignment(SWT.CENTER);
			lbltxt.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
			lbltxt.setFont(SWTResourceManager.getFont("Segoe UI", 15, SWT.BOLD));
		}

		Label lblEntrerLesCotation = new Label(container, SWT.NONE);
		lblEntrerLesCotation.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD));
		lblEntrerLesCotation.setText("Entrer les cotations li\u00E9es au dossier du patient " + personne.getPrenom() + " " + personne.getNom());

		Label lblRechercheNum = new Label(container, SWT.NONE);
		lblRechercheNum.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD));
		lblRechercheNum.setText("Recherche par numero ou description");

		tNum = new Text(container, SWT.BORDER);
		tNum.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		SimpleContentProposalProvider scpNum = new SimpleContentProposalProvider(null);
		try {
			adapter = new ContentProposalAdapter(tNum, new TextContentAdapter(), scpNum, KeyStroke.getInstance("Ctrl+Space"), null);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);

		tNum.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent ke) {
				if (ke.keyCode == 262144) {
					setAutoCompletion(tNum.getText());
				}
			}

		});

		// setAutoCompletion(tNum, null);
		//
		// tNum.addKeyListener(new KeyAdapter() {
		// public void keyReleased(KeyEvent ke) {
		// // Method for autocompletion
		// setAutoCompletion(tNum, tNum.getText());
		// }
		// });

		btnPlus = new Button(container, SWT.BORDER);
		btnPlus.setText("+");
		btnPlus.setToolTipText("Ajouter la cotation");
		btnPlus.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
		btnPlus.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				String tcotation = tNum.getText();
				if (tcotation.length() > 6) {
					String[] tabCot = tcotation.split("-");
					if (tabCot.length > 0) {
						TypeCotation tc = ReferentielServiceImpl.getInstance().getTypeCotationByLibelle(tabCot[0]);
						if (tc != null) {
							Cotation newCotation = new Cotation();
							newCotation.setTypeCotation(tc);
							newCotation.setPersonne(personne);
							ajouterLigne(newCotation);
						}

					}
				}
			}
		});

		Label lblRfrentielDesCotation = new Label(container, SWT.NONE);
		lblRfrentielDesCotation.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD));
		lblRfrentielDesCotation.setText("R\u00E9f\u00E9rentiel des cotations");

		table = new Table(container, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "cotation")) {
			table.addMouseListener(new MouseListener() {

				public void mouseUp(MouseEvent e) {
				}

				public void mouseDown(MouseEvent e) {
				}

				public void mouseDoubleClick(MouseEvent e) {
					int[] selections = table.getSelectionIndices();
					for (int j = 0; j < selections.length; j++) {
						int index = selections[j];
						Cotation newCotation = new Cotation();
						newCotation.setTypeCotation(typeCotations.get(index));
						newCotation.setPersonne(personne);
						ajouterLigne(newCotation);
					}
				}
			});
		}
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		data.minimumHeight = 200;
		table.setLayoutData(data);
		String[] titles = { "libelle", "description", "cotation" };
		for (int i = 0; i < titles.length; i++) {
			TableColumn column = new TableColumn(table, SWT.NONE);
			column.setText(titles[i]);
		}
		typeCotations = ReferentielServiceImpl.getInstance().getTypeCotation(null);
		if (typeCotations != null) {
			for (TypeCotation typeCotation : typeCotations) {
				TableItem item = new TableItem(table, SWT.NONE);
				item.setText(0, typeCotation.getLibelle());
				item.setText(1, typeCotation.getDescription());
				item.setText(2, typeCotation.getTypeB() + typeCotation.getQuantite());
			}
			for (int j = 0; j < titles.length; j++) {
				table.getColumn(j).pack();
			}
		}
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "cotation")) {
			Button btnAjouter = new Button(container, SWT.NONE);
			btnAjouter.setText("Ajouter les cotations selectionn\u00E9es");
			btnAjouter.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					int[] selections = table.getSelectionIndices();
					for (int j = 0; j < selections.length; j++) {
						int index = selections[j];
						Cotation newCotation = new Cotation();
						newCotation.setTypeCotation(typeCotations.get(index));
						newCotation.setPersonne(personne);
						ajouterLigne(newCotation);
					}
				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}
			});
		}
		Label lblCotations = new Label(container, SWT.NONE);
		lblCotations.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD));
		lblCotations.setText("Cotations :");

		tableCotation = new TableViewer(container, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
		ColumnViewerToolTipSupport.enableFor(tableCotation);
		createColumns();
		table_1 = tableCotation.getTable();
		table_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		table_1.setHeaderVisible(true);

		List<Cotation> cotations = CotationServiceImpl.getInstance().getCotationByidPersonne(personne.getIdPersonne());
		for (Cotation cotation : cotations) {
			ajouterLigne(cotation);
		}
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "cotation")) {
			Button btnSupprmier = new Button(container, SWT.NONE);
			btnSupprmier.setText("Supprimer les cotations selectionn\u00E9es");
			btnSupprmier.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					int[] selections = table_1.getSelectionIndices();
					if (selections != null) {
						if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirmation", "Etes-vous certain de vouloir supprimer les cotations selectionnées?")) {
							table_1.remove(selections);
							// tableCotation.refresh(true);
						}
					}

				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}
			});
		}
		return container;
	}

	// override method to use "Login" as label for the OK button
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "cotation")) {
			Button button = createButton(parent, IDialogConstants.OK_ID, "Créer", true);
			button.setText("Enregistrer");
		}
		createButton(parent, IDialogConstants.CANCEL_ID, "Annuler", false);
	}

	@Override
	protected Point getInitialSize() {
		return new Point(1108, 805);
	}

	@Override
	protected void okPressed() {

		TableItem[] items = tableCotation.getTable().getItems();
		CotationServiceImpl.getInstance().deleteAllByidPersonne(personne.getIdPersonne());
		for (TableItem item : items) {
			if (item.getData() instanceof Cotation) {
				Cotation c = (Cotation) item.getData();
				c.setIdCotation(0);
				CotationServiceImpl.getInstance().save(c);
			}
		}
		super.okPressed();
	}

	@Override
	protected void cancelPressed() {
		if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirmation", "Toutes les modifications apportées aux cotations ne seront pas sauvegardées. Etes-vous certain de vouloir quitter?")) {
			super.cancelPressed();
		}

	}

	private void ajouterLigne(Cotation cotation) {
		tableCotation.add(cotation);
	}

	private void setAutoCompletion(String value) {
		try {
			String[] defaultProposals = ReferentielServiceImpl.getInstance().getCotationFromString(value);
			if (defaultProposals.length > 0) {
				((SimpleContentProposalProvider) adapter.getContentProposalProvider()).setProposals(defaultProposals);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void createColumns() {
		String[] titles = { "Cotation", "Réalisé pour", "Date", "Envoyée" };
		int[] bounds = { 70, 350, 100, 120 };

		final TableViewerColumn column1 = createTableViewerColumn(titles[0], bounds[0], 0);
		column1.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				if (element instanceof Cotation)
					return ((Cotation) element).getTypeCotation().getLibelle();
				return super.getText(element);
			}

			@Override
			public String getToolTipText(Object element) {
				if (element instanceof Cotation)
					return ((Cotation) element).getTypeCotation().getTypeB() + ((Cotation) element).getTypeCotation().getQuantite() + ":" + ((Cotation) element).getTypeCotation().getDescription();
				return super.getText(element);
			}
		});
		column1.getColumn().addSelectionListener(new SortColumnListener(0));

		final TableViewerColumn column2 = createTableViewerColumn(titles[1], bounds[1], 1);
		column2.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof Cotation) {
					if (((Cotation) element).getAnalyse() != null) {
						Analyse ana = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse((((Cotation) element).getAnalyse()).getIdAnalyse());
						Prelevement pre = PrelevementServiceImpl.getInstance().getPrelevementById((((Cotation) element).getPrelevement()).getIdPrelevement());
						chaine = "Analyse : " + ana.getTypeAnalyse().getLibelle() + " n°" + ana.getIdAnalyse() + " du prélèvement : " + pre.getNumeroPrelevement();
					}
					if (((Cotation) element).getAnalyse() == null && ((Cotation) element).getPrelevement() != null) {
						Prelevement pre = PrelevementServiceImpl.getInstance().getPrelevementById((((Cotation) element).getPrelevement()).getIdPrelevement());
						if (pre != null) {
							chaine = "Prélèvement : " + pre.getNumeroPrelevement();
						}
					}
					if (((Cotation) element).getAnalyse() == null && ((Cotation) element).getPrelevement() == null) {
						chaine = "Dossier";
					}

				} else {
					chaine = super.getText(element);
				}
				return chaine;
			}
		});
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "cotation")) {
			column2.setEditingSupport(new CotationComboEditingSupport(tableCotation, personne.getIdPersonne()));
		}
		column2.getColumn().addSelectionListener(new SortColumnListener(1));

		final TableViewerColumn column3 = createTableViewerColumn(titles[2], bounds[2], 2);
		column3.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof Cotation) {
					if (((Cotation) element).getDate() != null) {
						SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
						chaine = formatDateJava.format(((Cotation) element).getDate());
					}
				} else {
					chaine = "";
				}
				return chaine;
			}
		});
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "cotation")) {
			column3.setEditingSupport(new CotationDateEditingSupport(tableCotation, personne.getIdPersonne()));
		}
		column3.getColumn().addSelectionListener(new SortColumnListener(2));

		final TableViewerColumn column4 = createTableViewerColumn(titles[3], bounds[3], 3);
		column4.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof Cotation) {
					if (((Cotation) element).getEnvoyer() != null) {
						SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
						chaine = "Envoyée le " + formatDateJava.format(((Cotation) element).getEnvoyer());
					} else {
						chaine = "Non envoyée";
					}

				} else {
					chaine = super.getText(element);
				}
				return chaine;
			}
		});
		column4.getColumn().addSelectionListener(new SortColumnListener(3));
	}

	private TableViewerColumn createTableViewerColumn(String header, int width, int idx) {
		TableViewerColumn column = new TableViewerColumn(tableCotation, SWT.LEFT, idx);
		column.getColumn().setText(header);
		column.getColumn().setWidth(width);
		column.getColumn().setResizable(true);
		column.getColumn().setMoveable(true);

		return column;
	}

	private class SortColumnListener implements SelectionListener {

		int idx;

		public SortColumnListener(int idx) {
			super();
			this.idx = idx;
		}

		@Override
		public void widgetSelected(SelectionEvent e) {
			TableItem[] items = tableCotation.getTable().getItems();
			Collator collator = Collator.getInstance(Locale.getDefault());
			for (int i = 1; i < items.length; i++) {
				String value1 = items[i].getText(idx);
				for (int j = 0; j < i; j++) {
					String value2 = items[j].getText(idx);
					if (collator.compare(value1, value2) < 0) {
						String[] values = { items[i].getText(0), items[i].getText(1), items[i].getText(2) };
						items[i].dispose();
						TableItem item = new TableItem(tableCotation.getTable(), SWT.NONE, j);
						item.setText(values);
						items = tableCotation.getTable().getItems();
						break;
					}
				}
			}
		}

		@Override
		public void widgetDefaultSelected(SelectionEvent e) {
			// TODO Auto-generated method stub

		}
	}
}
